#!/usr/bin/env python
# encoding: utf-8
"""
topic.py

Created by Ryan Delucchi on 2009-08-09.
Copyright (c) 2009 __MyCompanyName__. All rights reserved.
"""

import sys
import os
import re

from models import Topic

from google.appengine.ext import webapp
from google.appengine.api import urlfetch
import wsgiref.handlers

class MainHandler(webapp.RequestHandler):
    def get(self):
        topics = Topic.all().fetch(10)
        if topics == None:
            return
        
        # Write all topics in the datastore 
        # to the HTTP Response
        #for t in topics:
        #    self.response.out.write(t.text)
        
        content = ''
        for t in topics:
            #url = 'http://www.google.com/images?as_q=&hl=en&btnG=Google+Search&as_epq=&as_oq=' + t.text +
            #    '&as_eq=&imgtype=&imgsz=&imgw=&imgh=&as_filetype=&imgc=&as_sitesearch=&as_rights=&safe=images&as_st=y'
            
            q = t.text.replace(" ","+").replace("\t","+").replace("\n", "+").replace(":","%3a").replace("/","%2f");
            url = 'http://www.google.com/images?as_q=&hl=en&btnG=Google+Search&as_epq=&as_oq=' + q + '&as_eq=&imgtype=&imgsz=&imgw=&imgh=&as_filetype=&imgc=&as_sitesearch=&as_rights=&safe=images&as_st=y'            
            
            response = urlfetch.fetch(url)
            content = response.content + content
        
        #pattern = re.compile('imgurl=(.*?)\&')
        #items = pattern.match(content).split('&')
        items = content.split('&')
        
        self.response.out.write('<html><head><meta http-equiv=\"refresh\" content=\"10\"></head>')
        
        all = set([])
        for i in items:
            if 'imgurl' in i:
                if i.index('imgurl') not in all:
                    self.response.out.write('<img HEIGHT=\"150\", WIDTH=\"150\" src="' + i[i.index('imgurl') + 7:] + '"/>')
                    all.add(i.index('imgurl')) 
                    
        
        self.response.out.write('</html>')
        

if __name__ == '__main__':
    ### Configure the Web Application and run
    application = webapp.WSGIApplication([('/', MainHandler)],
                                     debug=True)
    wsgiref.handlers.CGIHandler().run(application)

